<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./style.css/car1.css">
    <link rel="stylesheet" href="./font-car/iconfont.css">
</head>

<body>
    <!-- 头部 -->
    <header>
        <div class="center">
            <div class="left">
                <span>OPPO官网</span>
                <span>一加官网</span>
            </div>
            <div class="right">
                <p>
                    <span>下载</span>
                    <span>0PP0</span>
                    <span>商城</span>
                    <span>App</span>
                </p>
                <!-- <div class="line"></div> -->
                <p>
                    <span class="iconfont icon-wode  pdenglu"></span>
                </p>
            </div>
    </header>
    <!-- 导航 -->
    <nav>
        <a href="#" class="img"><img src="./images/logo.img.png" alt=""></a>
        <div class="title">
            <a href="#">OPPO专区</a>
            <a href="#">OnePlus专区</a>
            <a href="#">智能硬件</a>
            <a href="#">服务</a>
        </div>
    </nav>
    <!-- 主体 -->
    <section>
        <div class="number">
            <p>已选择<i class="counts">0</i>件商品</p>
            <b>优惠券</b>
        </div>
        <div class="title">
            <p>商品信息</p>
            <div class="information">
                <span>单价</span>
                <span>数量</span>
                <span>小计</span>
                <span>操作</span>
            </div>
        </div>
        <div class="box1">
            <div class="carcontent">
                <div class="box2">
                    <span class="iconfont icon-tianmao2"></span>
                    <p>购物车还没有商品</p>
                    <a href="./index.html">去首页逛逛</a>
                </div>
            </div>
        </div>
        <div class="bigbox">

        </div>
    </section>
    <!-- 底部 -->
    <footer>
        <div class="VersionHeart">
            <div class="left">
                <input type="checkbox" class="check" id="all">
                <span>全选</span>
            </div>
            <div class="right">
                <dd>
                    <span>合计:</span>
                    <b>￥</b>
                    <p id="sum">0</p>
                </dd>
                <div class="Pay">
                    <p>结算</p>
                </div>
            </div>
        </div>
    </footer>
</body>
<script src="./js/_ajax.js"></script>
<script src="./js/ajax.js"></script>
<script src="./js/Cook.js"></script>
<script>
    // // 所有复选框
    var check = document.querySelectorAll('.check');
    var pdenglu = document.querySelector('.pdenglu');
    var checkLen = check.length;
    // 全选
    var allcheck = document.querySelector(".allcheck")
    // 商品前面的单个复选框     
    var single = document.querySelectorAll('.single')
    var singleLen = single.length;
    // 每一行商品
    var itemBox = document.querySelectorAll(".box");
    var itemBoxLen = itemBox.length;
    // 获取全选按钮
    var all = document.querySelector('#all')
    // 渲染框
    var bigbox = document.querySelector(".bigbox")
    // 单价
    var price = document.querySelector(".price")
    let goods = localStorage.getItem("goods");
    var Cook = getCookie("users");


    ajax({
        type: "get",
        url: "http://localhost:3000/myself?id=" + Cook,
        success: res => {
            console.log(res)
            if (JSON.parse(res).code != 0) {
                location.href = "http://localhost:3000/login.html"
            }
        },
        error: code => {
            console.log("error", code);
        }
    })


    ajax({
        type: "get",
        url: "http://localhost:3000/myself?id=" + Cook,
        success: (res) => {
            if (JSON.parse(res).code == 0) {
                pdenglu.innerHTML = "欢迎你" + "   " + `${JSON.parse(res).data.username}`;
                pdenglu.style.cursor = "pointer";
                pdenglu.style.cursor = "pointer";
                pdenglu.onclick = function () {
                    location.href = "myself.html";
                };
            }
        },
        error: (code) => {
            console.log("error", code);
        },
    });


    goods = goods ? JSON.parse(goods) : [];
    // console.log(goods)
    // console.log(goods)
    const pArr = [];


    // 遍历本地存储中获取到的数据
    // 根据id开启ajax请求
    // 并保存ajax请求开启之后的promise实例
    goods.forEach(val => {
        pArr.push(ajaxPromise("http://localhost:3000/soye?pid=" + val.id));

        // console.log(val)
    })
    // console.log(pArr)


    Promise.all(pArr).then(res => {
        // 因为后端给的数据是json字符，所以解析promise获取到的数据
        const arr = res.map(val => {
            return JSON.parse(val).data;
        })

        // 最终处理之后的数据
        // console.log(arr);
        // 根据数据，渲染页面
        let str = "";
        arr.forEach((val, idx) => {
            // console.log(val.pid)
            // console.log(val.price)
            // console.log(goods[idx].num)
            str +=
                `<div class="box" myid="${val.pid}">
            <div class="content">
                <input type="checkbox" class="single" ${goods[idx].check ? 'checked' : ''}>
                <dl>
                    <dt><img src="${val.url}"></dt>
                    <dd>
                        <p>${val.title}</p>
                        <li>
                            <b>白瓷，12G+256G,官方标配</b>
                            <div class="iconfont icon-xiangxia"></div>
                        </li>
                    </dd>
                </dl>
            </div>
            <div class="related">
                <div class="univalence">
                    <i>￥</i>
                    <span class="price">${val.price}</span>
                </div>
                <div class="quantity">
                    <span class="subtract">-</span>
                    <input type="text" value="${goods[idx].num}" oninput="value=value.replace(/[^\d]/g,'')" class="amount"
                        readonly="true" name="ches">
                    <span class="add">+</span>
                </div>
                <span class="subtotal">${val.price * goods[idx].num}</span>
                <p class="del">删除商品</p>
            </div>
        </div>`
        })
        bigbox.innerHTML = str

        if (bigbox.children.length == 0) {
            $(".box1").style.display = "block"
        } else {
            $(".box1").style.display = "none"
        }
        if (goods.length != 0) {
            $(".check").checked = goods.every(val => val.check);
        } else {
            $(".check").checked = false
        }
    })


    // // // 修改并记录选中状态
    bigbox.addEventListener("change", function (eve) {
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        if (target.className.includes("single")) {
            const id = target.parentNode.parentNode.getAttribute("myid");
            const check = target.checked;
            let i;
            goods.some((val, idx) => {
                i = idx;
                // console.log(val.id)
                // console.log(id)
                // console.log(idx)
                return val.id === id
            })
            // console.log(a)
            goods[i].check = check;

            localStorage.setItem("goods", JSON.stringify(goods));

            $(".check").checked = goods.every(val => val.check);


            // 计算总数量
            $(".counts").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num : 0), 0);
            // // 计算总价
            $("#sum").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num * val.price : 0), 0);
        }
    })



    // // 修改并记录数量
    bigbox.addEventListener("click", function (eve) {
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        if (target.className.includes("add")) {
            const id = target.parentNode.parentNode.parentNode.getAttribute("myid");

            let num1 = target.previousSibling.previousSibling.value - 0;
            let i;

            var subtotal = document.querySelectorAll(".subtotal")
            var amount = document.querySelectorAll(".amount")
            // goods.some((val, idx) => {
            //     i = idx;
            //     return val.id === id
            // })
            goods.forEach((val, idx) => {
                i = idx;
                if (val.id === id) {
                    goods[i].num++
                    amount[i].value = goods[i].num;
                    // console.log(goods[i].num)
                    // console.log(goods[i].price)
                    // console.log(subtotal[i])
                    // 计算小计
                    subtotal[i].innerHTML = goods[i].num * goods[i].price;
                    // console.log(subtotal[i].innerHTML)
                }
            })
            localStorage.setItem("goods", JSON.stringify(goods));

            // // 计算总数量
            $(".counts").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num : 0), 0);

            // // 计算总价
            $("#sum").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num * val.price : 0), 0);
        }
        if (target.className.includes("subtract")) {
            const id = target.parentNode.parentNode.parentNode.getAttribute("myid");

            let num1 = target.previousSibling.nextSibling.value - 0;
            let i;
            var subtotal = document.querySelectorAll(".subtotal")
            var amount = document.querySelectorAll(".amount")
            goods.forEach((val, idx) => {
                i = idx;
                if (val.id === id) {
                    if (amount[i].value > 1) {
                        goods[i].num--
                        amount[i].value = goods[i].num;
                        // 计算小计
                        subtotal[i].innerHTML = goods[i].num * goods[i].price
                    } else {
                        amount[i].value = 1
                        subtotal[i].innerHTML = goods[i].num * goods[i].price
                    }
                }
            })

            localStorage.setItem("goods", JSON.stringify(goods));


            // // 计算总数量
            $(".counts").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num : 0), 0);

            // // 计算总价
            $("#sum").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num * val.price : 0), 0);
        }
    }
    )



    // // 删除DOM并修改数据
    bigbox.addEventListener("click", function (eve) {
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        if (target.className.includes("del")) {
            // let id = target.parentNode.getAttribute("myid");
            target.parentNode.parentNode.remove();
            console.log(target.parentNode.parentNode.getAttribute("myid"))
            let i;
            goods.some((val, idx) => {
                i = idx;
                // console.log(val.id)
                console.log(target.parentNode.parentNode.getAttribute("myid"))
                return val.id === target.parentNode.parentNode.getAttribute("myid")
            })

            goods.splice(i, 1);

            localStorage.setItem("goods", JSON.stringify(goods));

            if (goods.length != 0) {
                $(".check").checked = goods.every(val => val.check);
            } else {
                $(".check").checked = false
            }

            // 计算总数量
            $(".counts").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num : 0), 0);

            // 计算总价
            $("#sum").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num * val.price : 0), 0);
            if (bigbox.children.length == 0) {
                $(".box1").style.display = "block"
            } else {
                $(".box1").style.display = "none"
            }
        }
    })

    // // 如果所有商品都被选中了，全选默认选中
    $(".check").checked = goods.every(val => val.check);

    // // 全选按钮影响单个商品的选中
    $(".check").onclick = function () {
        const all = document.querySelectorAll(".single");
        [...all].forEach(val => {
            val.checked = this.checked;
        })
        goods.forEach(val => {
            val.check = this.checked;
        })
        localStorage.setItem("goods", JSON.stringify(goods));

        // // 计算总数量
        $(".counts").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num : 0), 0);

        // // 计算总价
        $("#sum").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num * val.price : 0), 0);
    }

    // 计算小计
    // console.log($(".subtotal"))
    // $(".subtotal").innerHTML = goods.forEach((val, idx) => { goods[idx].price * goods[idx].num; })

    // 计算总数量
    $(".counts").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num : 0), 0);


    // 计算总价
    $("#sum").innerHTML = goods.reduce((prev, val) => prev + (val.check ? val.num * val.price : 0), 0);




    function $(s) {
        return document.querySelector(s);
    }

























    // 删除选中
    // $(".removeCheck").onclick = function(){
    //     goods = goods.filter(val=>!val.check);

    //     const all = document.querySelectorAll(".check");
    //     [...all].forEach(val=>{
    //         if(val.checked){
    //             val.parentNode.parentNode.remove();
    //         }
    //     })

    //     localStorage.setItem("goods", JSON.stringify(goods));

    //     // 计算总数量
    //     $(".allNum").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num : 0), 0);

    //     // 计算总价
    //     $(".allPrice").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num*val.price : 0), 0);
    // }



































    // for (var i = 0; i < checkLen; i++) {
    //     // 给所有复选框添加事件
    //     check[i].onclick = function (e) {

    //         // 选择的记录数
    //         var count = 0;
    //         // 判断得到全选
    //         if (e.target.getAttribute('id') == 'all') {
    //             // 把全选的状态赋值给每一个单选框
    //             for (var j = 0; j < singleLen; j++) {
    //                 single[j].checked = this.checked;
    //             }

    //         }
    //         for (var k = 0; k < singleLen; k++) {
    //             if (single[k].checked) {
    //                 count++;
    //             }
    //             if (count == single.length) {
    //                 all.checked = true;
    //             } else {
    //                 all.checked = false;
    //             }
    //         }
    //         fTotal();
    //     }
    // }


    // // var amount = document.querySelectorAll('.amount')
    // // 总数量和合计
    // function fTotal() {
    //     // 获取总价
    //     var total = document.querySelector('#sum')
    //     // 获取总件数
    //     var counts = document.querySelector('.counts');
    //     // 数量总和
    //     var totalNum = 0;
    //     // 总价
    //     price = 0;
    //     // 每一行商品
    //     var itemBox = document.querySelectorAll(".box");
    //     var itemBoxLen = itemBox.length;
    //     for (var i = 0; i < itemBoxLen; i++) {
    //         if (itemBox[i].getElementsByTagName('input')[0].checked) {
    //             totalNum += parseInt(itemBox[i].getElementsByTagName('input')[1].value);
    //             price += parseInt(itemBox[i].querySelector('.subtotal').innerHTML);
    //         }
    //     }
    //     counts.innerHTML = totalNum;
    //     total.innerHTML = price
    // }

    // // 给商品每一行添加事件
    // for (var i = 0; i < itemBoxLen; i++) {
    //     itemBox[i].onclick = function (e) {
    //         var input = this.getElementsByTagName('input')[1];
    //         switch (e.target.className) {
    //             case 'add':
    //                 input.value = parseInt(input.value) + 1;
    //                 fTotalSum(this);
    //                 break;
    //             case 'subtract':
    //                 input.value = parseInt(input.value) - 1 <= 1 ? 1 : parseInt(input.value) - 1;
    //                 fTotalSum(this);
    //                 break;
    //             case 'delete':
    //                 var con = confirm('确定删除么?');
    //                 if (con) {
    //                     this.parentNode.removeChild(this);
    //                 }
    //                 break;
    //         }
    //         // 调用:计算总数量和总价
    //         fTotal();
    //     }

    //     if (!itemBox[i]) {
    //         console.log(1)
    //     }
    // }


    // // 计算小计
    // function fTotalSum(that) {
    //     // 获取到当前行的数量
    //     var num = that.getElementsByTagName('input')[1].value;
    //     // 获取当前行的单价
    //     var price = that.querySelector('.price').innerHTML;
    //     // 小计的值
    //     that.querySelector('.subtotal').innerHTML = ` ${num * price}元`
    // }


</script>

</html>